package com.czumi.javawx.service;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.czumi.javawx.dao.entity.WeixinFan;
import com.czumi.javawx.dao.repository.WeixinFanRepository;
import com.czumi.javawx.util.EneityUtil;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;

@Service
public class WeixinFanService {

	@Autowired
	private WeixinFanRepository weixinFanRepository;

	/**
	 * 关注&取消更新粉丝信息
	 * 
	 * @param userinfo
	 */
	 @CacheEvict(value="spaj" ,key="'WeixinFan'")  
	public void saveAndUpdate(GetUserInfoResponse userinfo) {
		WeixinFan searchwx = new WeixinFan();
		searchwx.setOpenid(userinfo.getOpenid());
		Example<WeixinFan> example = Example.of(searchwx);
		WeixinFan rest = weixinFanRepository.findOne(example);
		WeixinFan weixinFan = new WeixinFan();
		if (userinfo.getSubscribe() == 0) {
			BeanUtils.copyProperties(rest, weixinFan);
			weixinFan.setSubscribe(userinfo.getSubscribe());
		} else {
			weixinFan = EneityUtil.convertWeixinFan(userinfo);
		}

		if (rest != null) {
			weixinFan.setId(rest.getId());
		}
		weixinFanRepository.saveAndFlush(weixinFan);
	}

	/**
	 * 程序更新粉丝信息
	 * 
	 * @param weixinFan
	 */
	 @CacheEvict(value="spaj" ,key="'WeixinFan'")  
	public void saveAndUpdate(List<WeixinFan> list) {
		for (WeixinFan weixinFan : list) {
			WeixinFan searchwx = new WeixinFan();
			searchwx.setOpenid(weixinFan.getOpenid());
			Example<WeixinFan> example = Example.of(searchwx);
			WeixinFan rest = weixinFanRepository.findOne(example);
			if(rest!=null) {
				rest.setHeadimgurl(weixinFan.getHeadimgurl());
				rest.setNickname(weixinFan.getNickname());
				weixinFanRepository.saveAndFlush(rest);
			}else {
				weixinFanRepository.saveAndFlush(weixinFan);
			}
		}
	}

	/**
	 * 获取所有粉丝信息
	 * 
	 * @return
	 */
	@Cacheable(value="spaj" ,key="'WeixinFan'") 
	public List<WeixinFan> getAllWeixinFans() {
		return weixinFanRepository.findAll();
	}

	

}
